package com.zoe.vhr.task;

import com.zoe.vhr.config.RabbitCallBack;
import com.zoe.vhr.enums.MailConfigEnum;
import com.zoe.vhr.model.Employee;
import com.zoe.vhr.model.MailSendLog;
import com.zoe.vhr.service.EmployeeService;
import com.zoe.vhr.service.MailSendLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zoe.Zhang
 * @date 2023/01/04
 * @description
 */
@Component
public class MailTask {
    @Resource
    private MailSendLogService mailSendLogService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private EmployeeService employeeService;

    @Scheduled(cron = "0/30 * * * * ?")
    public void mailTask() {
        // 去数据库中捞 发送失败的消息
        List<MailSendLog> mailSendLogs = mailSendLogService.getMailLogByStatus();
        for (MailSendLog mailSendLog : mailSendLogs) {
            String msgId = mailSendLog.getMsgId();
            // 判断有没有超过最大的重试次数
            if (mailSendLog.getCount() >= MailConfigEnum.MAX_TRY_COUNT) {
                mailSendLogService.updateSendLog(msgId, MailConfigEnum.FAILED);
            }
            else {
                Integer empId = mailSendLog.getEmpId();
                Employee employee = employeeService.getById(empId);
                // 把消息的发送次数自增+1 并且设置 下次重试时间,
                mailSendLogService.updateSendLogCountAndTryTime(msgId, new Date(System.currentTimeMillis() + MailConfigEnum.MSG_TIME_OUT));

                CorrelationData correlationData = new CorrelationData(msgId);
                correlationData.getFuture().addCallback(
                        RabbitCallBack.getConfirmSuccessCallback(msgId, correlationData),
                        RabbitCallBack.getFailureCallback(msgId, correlationData)
                );

                rabbitTemplate.convertAndSend(mailSendLog.getExchange(), mailSendLog.getRouteKey(), employee, correlationData);
            }
        }
    }
}
